import { useEffect, useState } from "react";
import { Switch, message, Popconfirm, Input, Checkbox, InputNumber } from "antd";
import { AttributeDescProps, OnOffDesc } from "@/components/render";

interface props {
  isLimit: boolean;
  kfData: any;
  setIsLimit: any;
  setKfLimit: any;
}

const { Search } = Input;

// 选择的所有员工
let totalUserList: any = [];
// 选择的员工
let selectedUsers: any = [];
// 是否全选
let allSelected: boolean = false;

const QrStaffLimit = ({ kfData, isLimit, setIsLimit, setKfLimit }: props) => {
  const [, setRender] = useState(0);
  const [disabledPop, setDisabledPop] = useState(false);
  const [batchNum, setBatchNum] = useState(100);
  let [serchKey, setSerchKey] = useState("");

  /* 是否开启上下限 */
  const isLimitChange = (e: boolean) => {
    if (selectedUsers.length) {
      setIsLimit(e);
    } else {
      message.warning("未添加使用成员，请先选择使用成员");
    }
  };

  // 名称搜索
  const serchUser = () => {
    if (!serchKey) {
      selectedUsers = JSON.parse(JSON.stringify(totalUserList));
    }
    selectedUsers = totalUserList.filter(
      (item: any) =>
        item.name.indexOf(serchKey) !== -1 || item.alias.indexOf(serchKey) !== -1
    );
    allSelected = selectedUsers.every((item: any) => {
      return item.limitSelected;
    });
    setRender(Math.random() + 1);
  };

  // 全选或者单选的操作
  const changeUser = ({ type, uid, flag }: any) => {
    let isAll: boolean = true;
    if (type === 1) {
      isAll = flag;
      selectedUsers.map((item: any) => {
        item.limitSelected = flag;
      });
    } else {
      selectedUsers.map((item: any) => {
        if (item.uid === uid) {
          item.limitSelected = flag;
        }
        if (!item.limitSelected) {
          isAll = false;
        }
      });
    }
    allSelected = isAll;
    totalUserList = JSON.parse(JSON.stringify(selectedUsers));
    setRender(Math.random() + 1);
  };

  // 调整数量
  const limitNum = ({ type, uid, num }: any) => {
    if (type === 1) {
      selectedUsers.map((item: any) => {
        if (item.limitSelected) {
          item.limit = num;
        }
      });
      totalUserList.map((item: any) => {
        if (item.limitSelected) {
          item.limit = num;
        }
      });
    } else {
      selectedUsers.map((item: any) => {
        if (item.uid === uid) {
          item.limit = num;
        }
      });
      totalUserList.map((item: any) => {
        if (item.uid === uid) {
          item.limit = num;
        }
      });
    }
    setKfLimit(totalUserList);
    setRender(Math.random() + 1);
  };

  useEffect(() => {
    // 接收其他组件改变选择的员工之后，产生的新的选择的员工数据
    window.globalState.getState("addUser", (value: any) => {
      console.log(value);

      // 挑出选择的员工
      let users = [];
      const { type } = value;
      if (type === 1) {
        users = value.user;
      } else {
        const { workCycles } = value;
        workCycles.map((item: any) => {
          users.push(...item.user);
        });
      }
      users.map((item: any) => {
        item.limit = 100;
      });

      if (users.length <= 0) {
        setIsLimit(false);
      }

      selectedUsers = JSON.parse(JSON.stringify(users));
      totalUserList = JSON.parse(JSON.stringify(users));
      setKfLimit(totalUserList);
      setRender(Math.random() + 1);
    });
    return () => {
      window.globalState.destoryState("addUser");
    };
  }, [setIsLimit, setKfLimit]);

  return (
    <div className="flex mb-24 items-start">
      <span className="w-106 text-right mr-16">员工添加上限:</span>
      <div className="w-634 flex flex-col items-start">
        {/* 开关 */}
        <div className="flex items-center justify-center">
          <Switch
            size="small"
            onChange={e => {
              isLimitChange(e);
            }}
            checked={isLimit}
          />
          <OnOffDesc flag={isLimit} />
        </div>

        {isLimit ? (
          <>
            {/* 说明 */}
            <AttributeDescProps
              attribute="员工添加上限："
              desc={[
                "员工从该渠道添加的客户达到每日上限后，将自动下线当日不再接待该渠道新客户",
              ]}
            />
            {/* 上限设置 */}
            {/* 员工搜索 */}
            <div className="w-full mb-8 flex relative justify-between items-center">
              <Search
                placeholder="请输入员工昵称"
                style={{ width: 320 }}
                onPressEnter={serchUser}
                onChange={(e: any) => {
                  setSerchKey(e.target.value.trim());
                  if (!e.target.value) {
                    serchKey = "";
                    serchUser();
                  }
                }}
              />
              <Popconfirm
                placement="bottomLeft"
                title={() => {
                  return (
                    <div>
                      <span>员工每日添加上限：</span>
                      <InputNumber
                        min={1}
                        max={100000}
                        defaultValue={batchNum}
                        onChange={(e: any) => {
                          setBatchNum(e);
                        }}
                      />
                    </div>
                  );
                }}
                onCancel={() => {
                  setDisabledPop(false);
                }}
                onConfirm={() => {
                  setDisabledPop(false);
                  limitNum({ type: 1, num: batchNum });
                }}
                icon={<></>}
                visible={disabledPop}
                okText="确认"
                cancelText="取消">
                <span
                  className="cursor-pointer text-blue-default"
                  onClick={() => {
                    if (
                      selectedUsers.length &&
                      selectedUsers.some((item: any) => item.limitSelected)
                    ) {
                      setDisabledPop(true);
                    } else {
                      setDisabledPop(false);
                      message.warning("请先选择一个成员");
                    }
                  }}>
                  批量设置
                </span>
              </Popconfirm>
            </div>

            {/* 员工列表 */}
            <div className=" mt12 w-full">
              {/* 列表头信息 */}
              <div className="bg-grey-200 h-36 w-full px-26 justify-between  flex items-center">
                <span>
                  <Checkbox
                    checked={allSelected}
                    onChange={(e: any) => {
                      changeUser({ type: 1, flag: e.target.checked });
                    }}>
                    共{selectedUsers.length}个员工
                  </Checkbox>
                </span>
                <span></span>
                <div>
                  <span>每日添加客户上限</span>
                </div>
              </div>

              {/* 员工上限设置列表 */}
              <ul className="rounded-b-sm border-1 border-solid border-grey-200 overflow-auto max-h-250 px-22 bg-white">
                {selectedUsers.map((item: any) => {
                  return (
                    <li
                      key={item.uid}
                      className="flex border-b-1 border-solid border-grey-200 items-center py-10">
                      <Checkbox
                        className="flex-1 flex items-center"
                        checked={item.limitSelected}
                        onChange={(e: any) => {
                          changeUser({ type: 2, uid: item.uid, flag: e.target.checked });
                        }}>
                        <div className="flex-1 flex items-center">
                          <img
                            alt=""
                            src={item.avatar}
                            className="w-28 h-28 rounded-2 ml-8"
                          />
                          <span className="flex-1 overflow-hidden overflow-ellipsis break-normal ml-12 ">
                            {item.name}
                          </span>
                        </div>
                      </Checkbox>
                      <div>
                        <InputNumber
                          min={1}
                          max={100000}
                          value={item.limit}
                          defaultValue={item.limit}
                          onChange={(e: any) => {
                            limitNum({ type: 2, uid: item.uid, num: e });
                          }}
                        />
                      </div>
                    </li>
                  );
                })}
              </ul>
            </div>
          </>
        ) : null}
      </div>
    </div>
  );
};

export default QrStaffLimit;
